package com.file;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 保存图书信息 {
  static class Book{
      private int id;
      private String name;
      private double price;
      Book(int id,String  name,double price){
          this.id = id;
          this.name = name;
          this.price = price;
      }

      @Override
      public String toString() {
          return "Book{" +
                  "id=" + id +
                  ", name='" + name + '\'' +
                  ", price=" + price +
                  '}';
      }
  }

    /**
     * 写入
     * @param books
     */
  public void write(List<Book> books,String path){
      FileWriter write = null;
      try {
          write = new FileWriter(path);

          for(Book book:books){
              write.write(book.toString()+"\r\n"); //换行

          }
      } catch (Exception e) {
          e.printStackTrace();
      } finally {

          try {
              write.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      }

    /**
     * 读取
     * @param path
     */
    public void read(String path){
        FileInputStream in = null;
        try {
            in = new FileInputStream(path);
            int i ;
            byte[] b = new byte[1024];
            while ((i = in.read(b)) != -1){
                System.out.println(new String(b));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        保存图书信息 save = new 保存图书信息();
        Book one = new Book(1,"红楼梦",10);
        Book two = new Book(2,"金瓶梅",20);
        Book three = new Book(3,"神雕侠侣",30);
        List<Book> list = Arrays.asList(one,two,three);
        String path = "d:\\7788\\fuck\\god.txt";
        save.write(list,path);
        save.read(path);


    }

}
